#include "lib.h"
#include "hashutils.h"


inline uint8 b2ah(uint8 i)
{
	if (i >= 0 && i <= 9)
	{
		return i + 48;
	}
	else if (i >= 10 && i <= 15)
	{
		return i + 55;
	}

	return 0;
}


String HashUtils::BinToStr(uint8* buffer, int size )
{
	char* strBuffer = new char[2*size+1];
	for(int32 i=0;i<size;i++)
	{
		strBuffer[2*i]   = b2ah((buffer[i] >> 4) & 0xF);
		strBuffer[2*i+1] = b2ah(buffer[i] & 0xF);
	}
	strBuffer[2*i] = 0;

	String result(strBuffer);
	delete[] strBuffer;
	return result;
}


String HashUtils::HashPassword(const String& password )
{
	// update shapassword on change
	uint8 shapassword[SHA1_DIGEST_SIZE];

	char utf8password[1024];
	StringConversions::encodeUTF8(utf8password, password, 1024);

	sha1(shapassword, (uint8*)utf8password, strlen(utf8password));

	return BinToStr(shapassword, SHA1_DIGEST_SIZE);
}
